package com.billard.service.impl;


import com.billard.mapper.OrderMapper;
import com.billard.mapper.TableMapper;
import com.billard.service.ReportService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 报表导出服务实现类
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private TableMapper tableMapper;

    @Override
    public void exportDailyRevenueReport(LocalDate date, HttpServletResponse response) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("每日营收报表");

            // 创建标题行

            Row headerRow = sheet.createRow(0);
            String[] headers = {"时间", "球台编号", "球台名称", "客户姓名", "使用时长(分钟)", "每小时价格", "总费用"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 查询当日订单数据
            LocalDateTime startTime = date.atStartOfDay();
            LocalDateTime endTime = date.atTime(23, 59, 59);
            List<Map<String, Object>> orders = orderMapper.selectDailyRevenueData(startTime, endTime);

            // 填充数据
            int rowNum = 1;
            BigDecimal totalRevenue = BigDecimal.ZERO;
            for (Map<String, Object> order : orders) {
                Row row = sheet.createRow(rowNum++);

                ((org.apache.poi.ss.usermodel.Row) row).createCell(0).setCellValue(order.get("startTime").toString());
                row.createCell(1).setCellValue(order.get("tableNumber").toString());
                row.createCell(2).setCellValue(order.get("tableName").toString());
                row.createCell(3).setCellValue(order.get("customerName").toString());
                row.createCell(4).setCellValue(order.get("duration").toString());
                row.createCell(5).setCellValue(order.get("hourlyPrice").toString());
                row.createCell(6).setCellValue(order.get("totalFee").toString());

                totalRevenue = totalRevenue.add((BigDecimal) order.get("totalFee"));
            }

            // 添加总计行
            Row totalRow = sheet.createRow(rowNum);
            totalRow.createCell(0).setCellValue("总计");
            totalRow.createCell(6).setCellValue(totalRevenue.toString());

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=daily_revenue_" + date + ".xlsx");

            // 输出文件
            workbook.write(response.getOutputStream());

        } catch (IOException e) {
            throw new RuntimeException("导出报表失败", e);
        }
    }

    @Override
    public void exportConsumptionReport(LocalDate startDate, LocalDate endDate, HttpServletResponse response) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("消费记录报表");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"订单号", "球台编号", "客户姓名", "开始时间", "结束时间", "使用时长(分钟)", "总费用", "状态"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 查询消费记录数据
            LocalDateTime startTime = startDate.atStartOfDay();
            LocalDateTime endTime = endDate.atTime(23, 59, 59);
            List<Map<String, Object>> orders = orderMapper.selectConsumptionData(startTime, endTime);

            // 填充数据
            int rowNum = 1;
            for (Map<String, Object> order : orders) {
                Row row = sheet.createRow(rowNum++);

                row.createCell(0).setCellValue(order.get("orderNumber").toString());
                row.createCell(1).setCellValue(order.get("tableNumber").toString());
                row.createCell(2).setCellValue(order.get("customerName").toString());
                row.createCell(3).setCellValue(order.get("startTime").toString());
                row.createCell(4).setCellValue(order.get("endTime").toString());
                row.createCell(5).setCellValue(order.get("duration").toString());
                row.createCell(6).setCellValue(order.get("totalFee").toString());
                row.createCell(7).setCellValue(getStatusDesc((Integer) order.get("status")));
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=consumption_report_" + startDate + "_" + endDate + ".xlsx");

            // 输出文件
            workbook.write(response.getOutputStream());

        } catch (IOException e) {
            throw new RuntimeException("导出报表失败", e);
        }
    }

    @Override
    public void exportTableUsageReport(LocalDate startDate, LocalDate endDate, HttpServletResponse response) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("球台使用统计报表");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"球台编号", "球台名称", "球台类型", "使用次数", "总使用时长(小时)", "总营收", "平均使用时长(小时)"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 查询球台使用统计数据
            LocalDateTime startTime = startDate.atStartOfDay();
            LocalDateTime endTime = endDate.atTime(23, 59, 59);
            List<Map<String, Object>> tableStats = tableMapper.selectTableUsageStats(startTime, endTime);

            // 填充数据
            int rowNum = 1;
            for (Map<String, Object> stat : tableStats) {
                Row row = sheet.createRow(rowNum++);

                row.createCell(0).setCellValue(stat.get("tableNumber").toString());
                row.createCell(1).setCellValue(stat.get("tableName").toString());
                row.createCell(2).setCellValue(getTypeDesc((Integer) stat.get("tableType")));
                row.createCell(3).setCellValue(stat.get("usageCount").toString());
                row.createCell(4).setCellValue(stat.get("totalHours").toString());
                row.createCell(5).setCellValue(stat.get("totalRevenue").toString());
                row.createCell(6).setCellValue(stat.get("avgHours").toString());
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=table_usage_report_" + startDate + "_" + endDate + ".xlsx");

            // 输出文件
            workbook.write(response.getOutputStream());

        } catch (IOException e) {
            throw new RuntimeException("导出报表失败", e);
        }
    }

    private String getStatusDesc(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 0: return "进行中";
            case 1: return "已结算";
            case 2: return "已取消";
            default: return "未知";
        }
    }

    private String getTypeDesc(Integer type) {
        if (type == null) return "";
        switch (type) {
            case 1: return "标准台";
            case 2: return "比赛台";
            case 3: return "VIP台";
            default: return "未知";
        }
    }
}
